package com.vito.dcs.report.service.impl;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.vito.base.authoriza.service.SectionService;
import com.vito.base.factory.IDFactory;
import com.vito.base.util.Validata;
import com.vito.dcs.common.util.SplitTableUtil;
import com.vito.dcs.report.dao.ReportStatisticsMapper;
import com.vito.dcs.report.service.ReportStatisticsService;
import com.vito.dcs.roller.statistics.dao.RollerStatisticsMapper;

@Service
public class ReportStatisticsServiceImpl implements ReportStatisticsService{

	@Autowired
	private ReportStatisticsMapper reportStatisticsMapper;
	@Autowired
	private RollerStatisticsMapper rollerStatisticsMapper;
	@Autowired
	private SectionService sectionService;
	
	@Override
	public String saveStatisticsReport(Map<String, Object> map) {
		
		/**
		 * 可以做一个限制，生成了就不再生成了，或者先删除，再生成新的报表，这样需传reportId
		 */
		map.put("tableName", SplitTableUtil.getTableName( (String)map.get("time") ));
		
		if(!Validata.isNullOrEmpty((String) map.get("reportId"))){
			reportStatisticsMapper.deleteTotalReport(map);
			reportStatisticsMapper.deleteTotalReportRoller(map);
			rollerStatisticsMapper.deleteRollerStatistics(map);
		}
		
		
		Map<String, Object> resMap = new HashMap<String, Object>();
		Map<String, Object> queryProjectName = reportStatisticsMapper.queryProjectName(map);
		resMap.putAll(queryProjectName);
		Map<String, Object> queryLayer = reportStatisticsMapper.queryLayer(map);
		resMap.putAll(queryLayer);
		
		if(queryLayer != null && !Validata.isNullOrEmpty((String) queryLayer.get("processType"))){
			map.put("processType", queryLayer.get("processType"));
		}
		
		Map<String, Object> queryTPJStart = reportStatisticsMapper.queryTPJStart(map);
		Map<String, Object> queryTPJEnd = reportStatisticsMapper.queryTPJEnd(map);
		
		if(queryTPJStart != null && queryTPJEnd != null){
			if(!Validata.isNullOrEmpty((String) queryTPJStart.get("current_mileage"))){
				//resMap.put("TPJStartMileage", queryTPJStart.get("current_mileage"));
				resMap.put("TPJStartTime", queryTPJStart.get("time"));
			}
			if(!Validata.isNullOrEmpty((String) queryTPJEnd.get("current_mileage"))){
				//resMap.put("TPJEndMileage", queryTPJEnd.get("current_mileage"));
				resMap.put("TPJEndTime", queryTPJEnd.get("time"));
			}
			if(!(Validata.isNullOrEmpty(queryTPJStart.get("cor_lng").toString()) && Validata.isNullOrEmpty(queryTPJStart.get("cor_lat").toString())
					&& Validata.isNullOrEmpty(queryTPJEnd.get("cor_lng").toString()) && Validata.isNullOrEmpty(queryTPJEnd.get("cor_lat").toString()))){
				double lantitudeLongitudeDist = CalculateDistance.LantitudeLongitudeDist(Double.parseDouble(queryTPJStart.get("cor_lng").toString()), Double.parseDouble(queryTPJStart.get("cor_lat").toString()), Double.parseDouble(queryTPJEnd.get("cor_lng").toString()), Double.parseDouble(queryTPJEnd.get("cor_lat").toString()));
				lantitudeLongitudeDist = Double.parseDouble(new DecimalFormat("###.###").format(lantitudeLongitudeDist));
				//lantitudeLongitudeDist = Double.parseDouble(new DecimalFormat("###.#####").format(lantitudeLongitudeDist));
				resMap.put("TPJMileage", lantitudeLongitudeDist);
				
				/*计算桩号*/
				Map<String,Object> rm2 = new HashMap<String, Object>();
				rm2.put("sectionId", map.get("sectionId"));
				rm2.put("longitude", queryTPJStart.get("cor_lng"));
				rm2.put("latitude", queryTPJStart.get("cor_lat"));
				String savePile2 = sectionService.savePile2(rm2);
				resMap.put("TPJStartMileage", savePile2);
				
				rm2.put("longitude", queryTPJEnd.get("cor_lng"));
				rm2.put("latitude", queryTPJEnd.get("cor_lat"));
				String savePile3 = sectionService.savePile2(rm2);
				resMap.put("TPJEndMileage", savePile3);
				
			}
		}
		
		int queryCurDateDataTotal = reportStatisticsMapper.queryCurDateDataTotal(map);
		int querySeriousSegregationCount = reportStatisticsMapper.querySeriousSegregationCount(map);
		int queryMildSegregationCount = reportStatisticsMapper.queryMildSegregationCount(map);
		if(queryCurDateDataTotal > 0){
			if("01".equals(map.get("processType"))){
				resMap.put("seriousSegregation", "--");
				resMap.put("mildSegregation", "--");
				resMap.put("notSegregation", "--"); 
			} else {
				/*处理数据*/
				double seriousSegregation = Double.parseDouble(new DecimalFormat("###.#####").format(querySeriousSegregationCount/(queryCurDateDataTotal*1.0)))*100.0;
				double mildSegregation = Double.parseDouble(new DecimalFormat("###.#####").format(queryMildSegregationCount/(queryCurDateDataTotal*1.0)))*100.0;
				double notSegregation = Double.parseDouble(new DecimalFormat("###.#####").format((queryCurDateDataTotal - queryMildSegregationCount - queryMildSegregationCount)/(queryCurDateDataTotal*1.0)))*100.0;
				resMap.put("seriousSegregation", seriousSegregation);
				resMap.put("mildSegregation", mildSegregation);
				resMap.put("notSegregation", notSegregation); 
			}

		} else {
			resMap.put("seriousSegregation", "--");
			resMap.put("mildSegregation", "--");
			resMap.put("notSegregation", "--"); 
		}
		
		int queryTPJDataTotal = reportStatisticsMapper.queryTPJDataTotal(map);
		if(queryTPJDataTotal > 0){
			Map<String, Object> queryMaxTPJData = reportStatisticsMapper.queryMaxTPJData(map);
			if(queryMaxTPJData != null){
				
				if("01".equals(map.get("processType"))){
					resMap.put("avgTPJTemperature", "--");
					resMap.put("maxTPJTemperature", "--");
					resMap.put("minTPJTemperature", "--"); 
					resMap.put("coeTPJTemperature", "--");
				} else {
					double maxTPJTemperature = Double.parseDouble(queryMaxTPJData.get("maxTPJTemperature").toString());
					double minTPJTemperature = Double.parseDouble(queryMaxTPJData.get("minTPJTemperature").toString());
					double all_temperature = Double.parseDouble(queryMaxTPJData.get("all_temperature").toString());
					
					double avgTPJTemperature = Double.parseDouble(new DecimalFormat("###.#####").format(all_temperature/(queryTPJDataTotal*1.0)));
					double coeTPJTemperature = maxTPJTemperature - minTPJTemperature;
					
					resMap.put("avgTPJTemperature", avgTPJTemperature);
					resMap.put("maxTPJTemperature", maxTPJTemperature);
					resMap.put("minTPJTemperature", minTPJTemperature); 
					resMap.put("coeTPJTemperature", coeTPJTemperature);
				}
				
				
				double maxTPJSpeed = Double.parseDouble(queryMaxTPJData.get("maxTPJSpeed").toString());
				double minTPJSpeed = Double.parseDouble(queryMaxTPJData.get("minTPJSpeed").toString());
				double all_run_speed = Double.parseDouble(queryMaxTPJData.get("all_run_speed").toString());
				
				double avgTPJSpeed = Double.parseDouble(new DecimalFormat("###.#####").format(all_run_speed/(queryTPJDataTotal*1.0)));
				double coeTPJSpeed = maxTPJSpeed - minTPJSpeed;
				
				resMap.put("avgTPJSpeed", avgTPJSpeed*60);
				resMap.put("maxTPJSpeed", maxTPJSpeed*60);
				resMap.put("minTPJSpeed", minTPJSpeed*60); 
				resMap.put("coeTPJSpeed", coeTPJSpeed*60);
				
			} else {
				resMap.put("avgTPJTemperature", "--");
				resMap.put("maxTPJTemperature", "--");
				resMap.put("minTPJTemperature", "--"); 
				resMap.put("coeTPJTemperature", "--");
				
				resMap.put("avgTPJSpeed", "--");
				resMap.put("maxTPJSpeed", "--");
				resMap.put("minTPJSpeed", "--"); 
				resMap.put("coeTPJSpeed", "--"); 
			}
		} else {
			resMap.put("avgTPJTemperature", "--");
			resMap.put("maxTPJTemperature", "--");
			resMap.put("minTPJTemperature", "--"); 
			resMap.put("coeTPJTemperature", "--"); 
			
			resMap.put("avgTPJSpeed", "--");
			resMap.put("maxTPJSpeed", "--");
			resMap.put("minTPJSpeed", "--"); 
			resMap.put("coeTPJSpeed", "--"); 
		}
		
		if("01".equals(map.get("processType"))){
			int queryWaterBlenderAlarm = reportStatisticsMapper.queryWaterBlenderAlarm(map);
			int queryGPSWaterAlarm = reportStatisticsMapper.queryGPSWaterAlarm(map);
			double waterAlarm = Double.parseDouble(new DecimalFormat("###.#####").format(queryGPSWaterAlarm/((queryWaterBlenderAlarm+queryGPSWaterAlarm)*1.0)))*100.0;
			resMap.put("warningPercent", waterAlarm);
			
		} else if ("02".equals(map.get("processType"))){
			int queryAsphaltBlenderAlarm = reportStatisticsMapper.queryAsphaltBlenderAlarm(map);
			int queryGPSAsphaltAlarm = reportStatisticsMapper.queryGPSAsphaltAlarm(map);
			double asphaltAlarm = Double.parseDouble(new DecimalFormat("###.#####").format(queryGPSAsphaltAlarm/((queryAsphaltBlenderAlarm+queryGPSAsphaltAlarm)*1.0)))*100.0;
			resMap.put("warningPercent", asphaltAlarm);
		}
		
		Map<String, Object> queryYLJStart = reportStatisticsMapper.queryYLJStart(map);
		Map<String, Object> queryYLJEnd = reportStatisticsMapper.queryYLJEnd(map);
		if(queryYLJStart != null && queryYLJEnd != null){
			//resMap.put("YLJStartMileage", queryYLJStart.get("current_mileage"));
			//resMap.put("YLJEndMileage", queryYLJEnd.get("current_mileage"));
			resMap.put("YLJStartMileage", resMap.get("TPJStartMileage"));
			resMap.put("YLJEndMileage", resMap.get("TPJEndMileage"));
			resMap.put("YLJStartTime", queryYLJStart.get("time"));
			resMap.put("YLJEndTime", queryYLJEnd.get("time"));
		}
		
		String reportId = IDFactory.getIDFactory().getIdInc("tbl_dcs_total_report") + "";
		resMap.put("id", reportId);
		
		resMap.putAll(map);
		
		reportStatisticsMapper.saveTotalReport(resMap);
		
		/**
		 * 处理压路机
		 */
		List<Map<String, Object>> queryYLJTotal = reportStatisticsMapper.queryYLJTotal(map);
		if(queryYLJTotal != null && queryYLJTotal.size() > 0){
			for (Map<String, Object> map2 : queryYLJTotal) {
				String id = IDFactory.getIDFactory().getIdInc("tbl_dcs_total_report_roller") + "";
				map2.put("id", id);
				map2.put("reportId", reportId);
				
				map2.put("sectionId", map.get("sectionId"));
				map2.put("time", map.get("time"));
				
				map2.put("tableName", map.get("tableName"));
				
				int querySingleYLJTotal = reportStatisticsMapper.querySingleYLJTotal(map2);
				if(querySingleYLJTotal > 0){
					Map<String, Object> querySingleYLJAll = reportStatisticsMapper.querySingleYLJAll(map2);
					double all_run_speed = Double.parseDouble(querySingleYLJAll.get("all_run_speed").toString());
					double all_temperature = 0.0;
					if("02".equals(map.get("processType"))){
						all_temperature = Double.parseDouble(querySingleYLJAll.get("all_temperature").toString());
					} else {
						all_temperature = 0.0;
					}
					
					double avgYLJSpeed = Double.parseDouble(new DecimalFormat("###.#####").format(all_run_speed/(querySingleYLJTotal*1.0)))*3.6;
					avgYLJSpeed = Double.parseDouble(new DecimalFormat("###.#####").format(avgYLJSpeed));
					map2.put("avgYLJSpeed", avgYLJSpeed);
					if("02".equals(map.get("processType"))){
						map2.put("avgYLJTemperature", Double.parseDouble(new DecimalFormat("###.#####").format(all_temperature/(querySingleYLJTotal*1.0))));
					} else {
						map2.put("avgYLJTemperature","--");
					}
					
					double overloadPercent = 0.0;
					if("01".equals(map.get("processType"))){
						int querySingleYLJWaterAlarm = reportStatisticsMapper.querySingleYLJWaterAlarm(map2);
						overloadPercent = Double.parseDouble(new DecimalFormat("###.#####").format(querySingleYLJWaterAlarm/(querySingleYLJTotal*1.0)))*100.0;
						
					} else if("02".equals(map.get("processType"))){
						int querySingleYLJAsphaltAlarm = reportStatisticsMapper.querySingleYLJAsphaltAlarm(map2);
						overloadPercent = Double.parseDouble(new DecimalFormat("###.#####").format(querySingleYLJAsphaltAlarm/(querySingleYLJTotal*1.0)))*100.0;
					}
					if(overloadPercent > 0){
						overloadPercent = Double.parseDouble(new DecimalFormat("###.#####").format(overloadPercent));
						map2.put("overloadPercent", overloadPercent);
					} else {
						map2.put("overloadPercent", "--");
					}
				} else {
					map2.put("avgYLJSpeed","--");
					map2.put("avgYLJTemperature","--");
					map2.put("overloadPercent","--");
				}
			}
		}
		reportStatisticsMapper.saveTotalReportRoller(queryYLJTotal);
		
		/**
		 * 处理遍数
		 */
		String paramJson = (String) map.get("paramJson");
		if(!Validata.isNullOrEmpty(paramJson)){
			@SuppressWarnings("unchecked")
			List<Map<String, Object>> list = (List<Map<String, Object>>)JSONArray.parse(paramJson);
			if(list != null && list.size() > 0){
				for (Map<String, Object> map2 : list) {
					String id = IDFactory.getIDFactory().getIdInc("tbl_dcs_roller_statistics") + "";
					map2.put("id", id);
					map2.put("reportId", reportId);
				}
				rollerStatisticsMapper.saveRollerStatistics(list);
			}
		}
		
		return reportId;
		
	}

	@Override
	public Map<String, Object> queryStatisticsReportTotal(
			Map<String, Object> map) {
		Map<String,Object> resMap = new HashMap<String, Object>();
		/**
		 * 传日期和标段
		 */
		Map<String, Object> queryTotalReport = reportStatisticsMapper.queryTotalReport(map);
		if(queryTotalReport != null){
			map.put("reportId", queryTotalReport.get("id"));
			List<Map<String, Object>> queryTotalReportRoller = reportStatisticsMapper.queryTotalReportRoller(map);
			List<Map<String, Object>> queryRollerStatisticsByReportId = rollerStatisticsMapper.queryRollerStatisticsByReportId(map);
			resMap.put("master", queryTotalReport);
			resMap.put("rollerPass", queryRollerStatisticsByReportId);
			resMap.put("roller", queryTotalReportRoller);
		}
		return resMap;
	}

}
